package bp.app.sugon.util;

import bp.app.sugon.entity.FlowTask;
import bp.da.DBAccess;
import bp.da.DataRow;
import bp.da.DataTable;
import bp.en.Attr;
import bp.en.Attrs;
import bp.wf.FlowEventBase;
import bp.wf.WorkAttr;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.chrono.ChronoLocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Hashtable;

/**
 * @Author: HANSZ
 * @Date: 2020-07-30 17:37
 * @Description:
 */
public class BaseDataUtil {

    /**
     * 组织数据
     *
     * @return 返回表单数据
     * @throws Exception
     */
    public static Hashtable<String, Comparable> setFormData(FlowEventBase flowEventBase) {
        Hashtable<String, Comparable> ht = new Hashtable<String, Comparable>();
        if (flowEventBase.HisEn == null) {
            return null;
        }
        try {
            Attrs attrs = flowEventBase.HisEn.getEnMap().getAttrs();
            for (Attr attr : attrs) {
                if (WorkAttr.Rec.equals(attr.getKey()) || WorkAttr.FID.equals(attr.getKey()) || WorkAttr.OID.equals(attr.getKey()) || WorkAttr.Emps.equals(attr.getKey()) || attr.getKey().equals("No") || attr.getKey().equals("Name")) {
                    continue;
                }
                ht.put(attr.getKey(), flowEventBase.HisEn.GetValByKey(attr.getKey()).toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ht;
    }

    /**
     * 取得主流程WorkID
     *
     * @param 当前流程WorkID
     * @return 主流程WorkID
     */
    public static Long getMainworkId(long WorkID) {
        String sql = "SELECT T2.WorkID, T2.Title ,t2.FK_Flow " +
                "FROM (  " +
                "SELECT  " +
                "    @r AS _id,  " +
                "    (SELECT @r := PWorkID FROM wf_generworkflow WHERE WorkID = _id) AS PWorkID,  " +
                "    @l := @l + 1 AS lvl  " +
                " FROM  " +
                "    (SELECT @r :=" + WorkID + ", @l := 0) vars,  " +
                "    wf_generworkflow h  " +
                " WHERE @r <> 0) T1  " +
                "JOIN wf_generworkflow T2  " +
                "ON T1._id = T2.WorkID  " +
                "ORDER BY T1.lvl DESC;";
        Long pworkId = 0L;
        DataTable mydt = DBAccess.RunSQLReturnTable(sql);
        if (mydt.Rows.size() > 1) {
            DataRow dremo = mydt.Rows.get(0);
            pworkId = Long.valueOf(dremo.getValue(0).toString());
        }

        return pworkId;
    }

    // 获取子流程中第二个节点的节点编号
    public static int getSubprocessNodeId(String subprocessNum) {
        int subprocess = Integer.parseInt(subprocessNum);
        return subprocess * 100 + 2;

    }

    public static boolean checkAddTask(FlowEventBase flowEventBase, String flowNo, long workId, int toNodeId, String userId) {
        //循环模式
        int runModel = flowEventBase.GetValInt("QDFS");
        if (runModel == 0) {
            return false;
        }
        Date endDate = flowEventBase.GetValDateTime("ZGSX");
        LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        if (LocalDate.now().isBefore(endLocalDate)) {
            Long mainWorkId = getMainworkId(workId);
            FlowTask flowTask = new FlowTask();
            flowTask.setWorkId(workId);
            flowTask.setUserId(userId);
            flowTask.setFlowNo(flowNo);
            flowTask.setToNodeId(toNodeId);
            flowTask.setStatus(0);
            flowTask.setCreateTime(new Date());
            flowTask.setMainWorkId(mainWorkId);
            LocalDateTime newTime;
            switch (runModel) {
                case 1:
                    // 每天反馈
                    newTime = LocalDateTime.now().plusDays(1);
                    break;
                case 2:
                    // 每周反馈
                    int severalWeek = flowEventBase.GetValInt("ZQDMS");
                    newTime = byWeek(++severalWeek);

                    break;
                case 3:
                    // 每月反馈
                    newTime = LocalDateTime.now().plusMonths(1);
                    break;
                default:
                    return false;
            }
            if (newTime.toLocalDate().isAfter(endLocalDate)) {
                return false;
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String sql = "insert into flow_task (work_id, main_work_id, user_id, flow_no, to_node_id, status, issued_time, create_time) values (" + flowTask.getWorkId() + "," + flowTask.getMainWorkId() + ",'" + flowTask.getUserId() + "','" + flowTask.getFlowNo() + "'," + flowTask.getToNodeId() + "," + flowTask.getStatus() + ",'" + formatter.format(newTime) + "', now())";
            DBAccess.RunSQL(sql);
            return true;
        }
        return false;
    }

    /**
     * @Author: HANSZ
     * @Date: 2020-08-18 13:41
     * @Description: 获取下周的周几
     */
    private static LocalDateTime byWeek(int dictionaryWeek) {
        int day;
        int value = LocalDate.now().getDayOfWeek().getValue();
        if (dictionaryWeek == value) {
            day = 7;
        } else if (value < dictionaryWeek) {
            day = dictionaryWeek - value + 7;
        } else {
            day = 7 - (value - dictionaryWeek);
        }
        return LocalDateTime.now().plusDays(day);
    }
}
